//
//  UATStarter.m
//  Pods-UStarter_Example
//
//  Created by Mark on 2021/1/7.
//

#import "UATStarter.h"
#import "UATLaunchController.h"


// 引入 JPush 功能所需头文件
#import <JPush/JPUSHService.h>
// iOS10 注册 APNs 所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
// 如果需要使用 idfa 功能所需要引入的头文件（可选）
#import <AdSupport/AdSupport.h>

@interface UATStarter()<JPUSHRegisterDelegate>



@end

@implementation UATStarter

static UATStarter * _instance = nil ;

+ (instancetype) shareInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[super allocWithZone:NULL] init];
    });
    return _instance ;
}

+ (id) allocWithZone:(struct _NSZone *)zone {
    return [UATStarter shareInstance];
}


+ (instancetype) setupWithLaunchConfig:(UATLaunchConfig *)launchConfig
                       thirdPartConfig:(nullable UATThirdPartConfig *)thirdPartConfig
                           application:(UIApplication *)application
                             keywindow:(nonnull UIWindow *)kw{
    UATStarter * starter = [UATStarter shareInstance];
    
    Class launchVCClass = [launchConfig launchPageClazz];
    // 初始控制器
    id launchVC  ;
    if([launchVCClass isSubclassOfClass:[UATLaunchController class]]){
        launchVC = [([launchVCClass alloc]) initWithLaunchOptions:launchConfig.launchOpts];
    }else{
        NSLog(@"launch vc class is not subclass of UATLaunchController");
    }
    
    // 根视图
//    UATNavigator * root=[((UATNavigator*)[launchConfig.rootNavigationClass alloc]) initWithRootViewController: launchVC];
    UINavigationController * root= launchConfig.rootController;
    
    [starter setNavigator:root];
    
    NSMutableArray<Class> * whiteList =[NSMutableArray arrayWithArray:launchConfig.accessWihteList];
    
    [whiteList addObject:[root.topViewController class]];
    launchConfig.accessWihteList =whiteList ;
    [starter setApplication:application];
    [starter setLaunchConfig:launchConfig];
    [starter setThirdPartConfig:thirdPartConfig];
    
    starter.delegate = application ;
    
    if(kw==nil){
        kw = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    }
    [kw setRootViewController:root];
    [kw makeKeyAndVisible];
    
    [starter setupThirdPart];
    
    if(launchConfig.launchOpts!=nil){
        DLog(@"launch with param :%@",launchConfig.launchOpts);
    }
    
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:starter selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
    
    return starter ;
}


+ (void) setupRequestConfig:(UATRequestConfig *)requestConfig {
    [UATStarter shareInstance].requestConfig = requestConfig ;
}


+ (UATNavigator*) shareRoute ; {
    return [[UATStarter shareInstance] navigator];
}


- (void) setupThirdPart{
    
    UATThirdPartConfig * config = self.thirdPartConfig ;
    
    if(config.jiguangSetupConfig!=nil){
        [JiguangSetupConfig setup:config.jiguangSetupConfig delegate:self];
    }
}

/*
 * @brief handle UserNotifications.framework [willPresentNotification:withCompletionHandler:]
 * @param center [UNUserNotificationCenter currentNotificationCenter] 新特性用户通知中心
 * @param notification 前台得到的的通知对象
 * @param completionHandler 该callback中的options 请使用UNNotificationPresentationOptions
 */
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger options))completionHandler;{
    DLog(@"----->call:willPresentNotification");
    completionHandler(1);
}
/*
 * @brief handle UserNotifications.framework [didReceiveNotificationResponse:withCompletionHandler:]
 * @param center [UNUserNotificationCenter currentNotificationCenter] 新特性用户通知中心
 * @param response 通知响应对象
 * @param completionHandler
 */
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler;{
    DLog(@"----->call:didReceiveNotificationResponse");
    completionHandler();
}

/*
 * @brief handle UserNotifications.framework [openSettingsForNotification:]
 * @param center [UNUserNotificationCenter currentNotificationCenter] 新特性用户通知中心
 * @param notification 当前管理的通知对象
 */
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification NS_AVAILABLE_IOS(12.0);{
    DLog(@"----->call:openSettingsForNotification");
}


+ (void) registerDeviceToken:(NSData *)token {
    UATThirdPartConfig * config = [[UATStarter shareInstance] thirdPartConfig];
    if(config.jiguangSetupConfig!=nil){
        [JPUSHService registerDeviceToken:token];
    }
}


- (void)networkDidReceiveMessage:(NSNotification *)notification {
    if([self.delegate respondsToSelector:@selector(onJiguangCustomNotification:)]){
        [self.delegate onJiguangCustomNotification:notification];
    }else{
        DLog(@"实现接口networkDidReceiveMessage，监听极光自定义消息");
    }
}



- (UATRequestConfig*)requestConfig{
    UATRequestConfig * config = _requestConfig;
    if(config==nil){
        config = [[UATRequestConfig alloc] initWithGlobalParam:@{} scope:UATRequestConfigScopeURL baseUrl:@""];
        return config;
    }
    return config;
}


@end
